const VideoModel = require('../models/videoModel');
const { generateMD5, validateRequiredFields } = require('../utils/helpers');
const { autoTranscodeIfNeeded } = require('../utils/videoTranscoder');
const logger = require('../utils/logger');
const path = require('path');
const fs = require('fs');

class VideoController {
  // 上传视频（管理端）
  static async uploadVideo(req, res) {
    try {
      // 如果只上传文件用于获取 URL（未携带必要元信息），直接返回 URL，不入库
      if (req.file && (!req.body || (!req.body.title && !req.body.copyright_type))) {
        const base = process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`;
        const videoFilePath = req.file.path;
        let transcodeInfo = null;
        
        // 检查并自动转码视频（如果需要）
        try {
          logger.info('检查视频是否需要转码:', videoFilePath);
          transcodeInfo = await autoTranscodeIfNeeded(videoFilePath, {
            replaceOriginal: true  // 转码后替换原文件
          });
          
          if (transcodeInfo.transcoded) {
            logger.info('视频已转码:', transcodeInfo);
          }
        } catch (transcodeError) {
          // 转码失败不影响上传流程
          logger.error('视频转码失败（继续使用原视频）:', transcodeError);
        }
        
        const fileUrl = `${base}/uploads/videos/${encodeURIComponent(req.file.filename)}`;
        return res.json({
          code: 200,
          msg: req.fileExisted ? '视频已存在，复用' : '视频上传成功',
          data: { 
            url: fileUrl, 
            existed: !!req.fileExisted,
            transcoded: transcodeInfo?.transcoded || false,
            transcodeInfo: transcodeInfo
          }
        });
      }

      // 验证必需字段（入库场景）
      validateRequiredFields(req.body, ['title', 'copyright_type']);
      
      // 检查 genre_ids 是否为数组
      let genreIds = [];
      if (req.body.genre_ids) {
        if (Array.isArray(req.body.genre_ids)) {
          genreIds = req.body.genre_ids;
        } else if (typeof req.body.genre_ids === 'string') {
          // 如果是逗号分隔的字符串，转换为数组
          genreIds = req.body.genre_ids.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
        }
      }
      
      if (genreIds.length === 0) {
        return res.status(400).json({
          code: 400,
          msg: '至少选择一个剧种'
        });
      }
      
      // 生成视频唯一标识
      const videoId = generateMD5(`${req.body.title}-${Date.now()}`);
      
      // 获取文件路径
      let videoUrl = req.body.video_url;
      let coverUrl = req.body.cover_url || '';
      let transcodeInfo = null;
      
      if (req.file) {
        const base = process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`;
        const videoFilePath = req.file.path;
        
        // 检查并自动转码视频（如果需要）
        try {
          logger.info('检查视频是否需要转码:', videoFilePath);
          transcodeInfo = await autoTranscodeIfNeeded(videoFilePath, {
            replaceOriginal: true  // 转码后替换原文件
          });
          
          if (transcodeInfo.transcoded) {
            logger.info('视频已转码:', transcodeInfo);
          } else {
            logger.info('视频无需转码:', transcodeInfo.reason);
          }
        } catch (transcodeError) {
          // 转码失败不影响上传流程，只记录错误
          logger.error('视频转码失败（继续使用原视频）:', transcodeError);
        }
        
        videoUrl = `${base}/uploads/videos/${encodeURIComponent(req.file.filename)}`;
      }
      
      // 构造视频数据
      const videoData = {
        id: videoId,
        title: req.body.title,
        description: req.body.description || '',
        source: req.body.source || '',
        copyright_type: req.body.copyright_type,
        video_url: videoUrl,
        cover_url: coverUrl,
        genre_ids: genreIds
      };
      
      // 保存到数据库
      await VideoModel.create(videoData);
      
      res.json({
        code: 200,
        msg: '视频上传成功',
        data: { 
          id: videoId,
          video_url: videoUrl
        }
      });
    } catch (error) {
      console.error('上传视频失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 编辑视频（管理端）
  static async editVideo(req, res) {
    try {
      const { id } = req.params;
      
      if (!id) {
        return res.status(400).json({
          code: 400,
          msg: '缺少视频ID'
        });
      }
      
      // 可选字段更新：仅更新传入的字段
      const updateData = {};
      const updatableKeys = ['title', 'description', 'source', 'copyright_type', 'video_url', 'cover_url'];
      updatableKeys.forEach((key) => {
        if (typeof req.body[key] !== 'undefined') {
          updateData[key] = req.body[key];
        }
      });

      // 地区关联已移除，视频不再关联地区

      // 检查 genre_ids 是否为数组（可选）
      let genreIds = [];
      if (typeof req.body.genre_ids !== 'undefined') {
        if (Array.isArray(req.body.genre_ids)) {
          genreIds = req.body.genre_ids;
        } else if (typeof req.body.genre_ids === 'string') {
          // 如果是逗号分隔的字符串，转换为数组
          genreIds = req.body.genre_ids.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
        }
      }

      if (genreIds.length > 0) {
        updateData.genre_ids = genreIds;
      }

      if (Object.keys(updateData).length === 0) {
        return res.status(400).json({ code: 400, msg: '没有可更新的字段' });
      }

      // 更新数据库
      await VideoModel.update(id, updateData);
      
      res.json({
        code: 200,
        msg: '视频更新成功'
      });
    } catch (error) {
      console.error('编辑视频失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 删除视频（管理端）
  static async deleteVideo(req, res) {
    try {
      const { id } = req.params;
      
      if (!id) {
        return res.status(400).json({
          code: 400,
          msg: '缺少视频ID'
        });
      }
      
      // 删除数据库记录
      await VideoModel.delete(id);
      
      res.json({
        code: 200,
        msg: '视频删除成功'
      });
    } catch (error) {
      console.error('删除视频失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 获取视频列表（管理端）
  static async getVideoList(req, res) {
    try {
      const { page = 1, pageSize = 20, search = '' } = req.query;
      
      const result = await VideoModel.getList(
        parseInt(page),
        parseInt(pageSize),
        search
      );
      
      res.json({
        code: 200,
        msg: '获取成功',
        data: result
      });
    } catch (error) {
      console.error('获取视频列表失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 获取视频详情
  static async getVideoDetail(req, res) {
    try {
      const { id } = req.params;
      
      if (!id) {
        return res.status(400).json({
          code: 400,
          msg: '缺少视频ID'
        });
      }
      
      const video = await VideoModel.findById(id);
      
      if (!video) {
        return res.status(404).json({
          code: 404,
          msg: '视频不存在'
        });
      }
      
      res.json({
        code: 200,
        msg: '获取成功',
        data: video
      });
    } catch (error) {
      console.error('获取视频详情失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 增加播放次数
  static async increasePlayCount(req, res) {
    try {
      const { id } = req.params;
      
      if (!id) {
        return res.status(400).json({
          code: 400,
          msg: '缺少视频ID'
        });
      }
      
      await VideoModel.incrementPlayCount(id);
      
      res.json({
        code: 200,
        msg: '播放次数增加成功'
      });
    } catch (error) {
      console.error('增加播放次数失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 搜索视频
  static async searchVideos(req, res) {
    try {
      const { keyword, page = 1, pageSize = 20 } = req.query;
      
      if (!keyword) {
        return res.status(400).json({
          code: 400,
          msg: '缺少搜索关键词'
        });
      }
      
      const result = await VideoModel.search(
        keyword,
        parseInt(page),
        parseInt(pageSize)
      );
      
      res.json({
        code: 200,
        msg: '搜索成功',
        data: result
      });
    } catch (error) {
      console.error('搜索视频失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 获取推荐视频
  static async getRecommendedVideos(req, res) {
    try {
      const { page = 1, pageSize = 20 } = req.query;
      
      const result = await VideoModel.getRecommended(
        parseInt(page),
        parseInt(pageSize)
      );
      
      res.json({
        code: 200,
        msg: '获取成功',
        data: result
      });
    } catch (error) {
      console.error('获取推荐视频失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 按区域获取视频
  static async getVideosByArea(req, res) {
    try {
      const { areaId } = req.params;
      const { page = 1, pageSize = 20 } = req.query;
      
      if (!areaId) {
        return res.status(400).json({
          code: 400,
          msg: '缺少区域ID'
        });
      }
      
      const result = await VideoModel.getByAreaId(
        areaId,
        parseInt(page),
        parseInt(pageSize)
      );
      
      res.json({
        code: 200,
        msg: '获取成功',
        data: result
      });
    } catch (error) {
      console.error('按区域获取视频失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 按剧种获取视频
  static async getVideosByGenre(req, res) {
    try {
      const { genreId } = req.params;
      const { page = 1, pageSize = 20 } = req.query;
      
      if (!genreId) {
        return res.status(400).json({
          code: 400,
          msg: '缺少剧种ID'
        });
      }
      
      const result = await VideoModel.getByGenreId(
        genreId,
        parseInt(page),
        parseInt(pageSize)
      );
      
      res.json({
        code: 200,
        msg: '获取成功',
        data: result
      });
    } catch (error) {
      console.error('按剧种获取视频失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }

  // 手动转码视频（管理端）
  static async transcodeVideo(req, res) {
    try {
      const { id } = req.params;
      
      if (!id) {
        return res.status(400).json({
          code: 400,
          msg: '缺少视频ID'
        });
      }

      // 获取视频信息
      const video = await VideoModel.findById(id);
      if (!video) {
        return res.status(404).json({
          code: 404,
          msg: '视频不存在'
        });
      }

      // 从 URL 中提取文件名
      const videoUrl = video.video_url;
      const filename = decodeURIComponent(videoUrl.split('/').pop());
      const videoFilePath = path.join(__dirname, '../uploads/videos', filename);

      // 检查文件是否存在
      if (!fs.existsSync(videoFilePath)) {
        return res.status(404).json({
          code: 404,
          msg: '视频文件不存在'
        });
      }

      logger.info('手动转码视频:', { id, videoFilePath });

      // 执行转码
      const transcodeInfo = await autoTranscodeIfNeeded(videoFilePath, {
        replaceOriginal: true,  // 替换原文件
      });

      res.json({
        code: 200,
        msg: transcodeInfo.transcoded ? '视频转码成功' : '视频无需转码',
        data: transcodeInfo
      });

    } catch (error) {
      logger.error('转码视频失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '视频转码失败'
      });
    }
  }

  // 批量检查视频是否需要转码（管理端）
  static async checkVideosTranscode(req, res) {
    try {
      const { page = 1, pageSize = 20 } = req.query;
      
      // 获取视频列表
      const result = await VideoModel.getList(parseInt(page), parseInt(pageSize));
      
      const videoTranscoder = require('../utils/videoTranscoder');
      const checkResults = [];

      // 检查每个视频
      for (const video of result.list) {
        try {
          const videoUrl = video.video_url;
          const filename = decodeURIComponent(videoUrl.split('/').pop());
          const videoFilePath = path.join(__dirname, '../uploads/videos', filename);

          if (fs.existsSync(videoFilePath)) {
            const check = await videoTranscoder.checkNeedsTranscode(videoFilePath);
            checkResults.push({
              id: video.id,
              title: video.title,
              needsTranscode: check.needsTranscode,
              reason: check.reason,
              codec: check.metadata?.codec_name,
              profile: check.metadata?.profile
            });
          } else {
            checkResults.push({
              id: video.id,
              title: video.title,
              error: '文件不存在'
            });
          }
        } catch (error) {
          checkResults.push({
            id: video.id,
            title: video.title,
            error: error.message
          });
        }
      }

      const needsTranscodeCount = checkResults.filter(r => r.needsTranscode).length;

      res.json({
        code: 200,
        msg: '检查完成',
        data: {
          total: result.total,
          checked: checkResults.length,
          needsTranscode: needsTranscodeCount,
          list: checkResults
        }
      });

    } catch (error) {
      logger.error('检查视频转码失败:', error);
      res.status(500).json({
        code: 500,
        msg: error.message || '服务器错误'
      });
    }
  }
}

module.exports = VideoController;